<?php

class ButtonList extends CWidget {
	
	public $model;
	public $form;
	public $attribute;
	public $data = array();
	public $itemTemplate = '<li class="{currentClass}" key="{key}">{value}</li>';
	public $itemCurrentClass = 'current';
	public $tagName = 'ul';
	public $clearfix = true;
	public $wrapperHtml = array();
	
	private static $_counter = 0;
	
	public function run() {
		list($model, $attribute, $htmlOptions) = 
			CActiveFormAdv::resolveArgs($this->model, $this->attribute);
		$attrValue = $model->$attribute;
		$itemHtml = '';
		foreach($this->data as $k=>$v) {
			$hoverClass = $k == $attrValue ? $this->itemCurrentClass : '';
			$itemHtml .= str_replace(
				array('{currentClass}', '{key}', '{value}'),
				array($hoverClass, $k, $v), 
				$this->itemTemplate
			);
		}
		
		$id = 'buttonlist_'.(++self::$_counter);
		$hiddenId = 'hide_'.$id;
		
		$wrapper = CHtml::tag($this->tagName, array_merge(array(
			'class' => 'button-list',
			'id' => $id,
		), $this->wrapperHtml), $itemHtml, $this->tagName);
		
		if($this->clearfix) $wrapper.='<div class="bh-clear"></div>';
		
		$hidden = $this->form->hiddenField(
			$this->model, 
			$this->attribute, 
			array('id'=>$hiddenId)
		);
		
		$cs = Yii::app()->clientScript;
		$cs->registerScriptFile(
			Yii::app()->assetManager->publish(
				dirname(__FILE__).'/js/jquery.buttonlist.js'
			)
		);
		
		$script = "$('#{$id}').buttonList({itemCurrentClass: '{$this->itemCurrentClass}', hiddenId: '{$hiddenId}'})";
		$cs->registerScript($id, $script, CClientScript::POS_END);
		
		echo $wrapper.$hidden;
	}
	

}

?>